//
//  LCWStatus.swift
//  MyWB
//
//  Created by 李成万 on 16/6/27.
//  Copyright © 2016年 李成万. All rights reserved.
//

import UIKit

class LCWStatus: NSObject {

    var created_at:String?
    
    var createAt : String?{
        return getTime(created_at ?? "")
    }
    
    var id: Int64 = 0
    
    var text: String?{
        didSet{
            attrString = getWeiBoAttr(text ?? "")
        }
    }
    
    var source: String?{
        didSet{
            sourceAttr = getSource(source)
        }
    }
    var sourceAttr:NSMutableAttributedString?
    
    var user:LCWUser?
    
    var retweeted_status:LCWStatus?
    
    /*
    reposts_count	int	转发数
    comments_count	int	评论数
    attitudes_count
    */
    var reposts_count : Int = 0{
        didSet{
            reposts_count_str = getZhuanPingZanStr(reposts_count, title: "转发")
        }
    }
    var comments_count: Int = 0{
        didSet{
            comments_count_str = getZhuanPingZanStr(comments_count, title: "评论")
        }
    }
    var attitudes_count: Int = 0{
        didSet{
            attitudes_count_str = getZhuanPingZanStr(attitudes_count, title: "赞")
        }
    }
    
    var reposts_count_str : String?
    var comments_count_str : String?
    var attitudes_count_str : String?
    
    /// 定义元素为 LCWPicInfo 的数组
    var pic_urls:[LCWPicInfo]?
    
    var attrString : NSMutableAttributedString?
    
    
    init(dict:[String:AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user"{
            guard let v = value as? [String:AnyObject] else{
                return
            }
            let u = LCWUser(dict: v)
            user = u
        }else if key == "retweeted_status"{
            
            guard let v = value as? [String:AnyObject] else{
                return
            }
            let u = LCWStatus(dict: v)
            retweeted_status = u
            
        }else if key == "pic_urls"{
            guard let v = value as? [[String:AnyObject]] else{
                return
            }
            var tempArr : [LCWPicInfo] = [LCWPicInfo]()
            for dic in v{
                let picInfo  = LCWPicInfo(dict: dic)
                tempArr.append(picInfo)
            }
            pic_urls = tempArr
            
        }else{
            super.setValue(value, forKey: key)
        }
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    func getZhuanPingZanStr(count:Int,title:String) -> String{
        if count > 0 && count < 10000{
            return "\(count)"
        }else if count == 0 {
            return title
        }else{
            let countF : CGFloat = CGFloat(count/1000)/10
            var countStr : String = "\(countF)万"
            
            if countStr.containsString(".0"){
                 countStr = countStr.stringByReplacingOccurrencesOfString(".0", withString: "")
            }
            return countStr
        }
    }
    /// 截取 source 方法
    func getSource(source:String?) ->NSMutableAttributedString{
        //"<a href=\"http://app.weibo.com/t/feed/6vtZb0\" rel=\"nofollow\">微博 weibo.com</a>"
        guard let s = source where s.containsString("\">") else{
            return getSourceAttr("")
        }
        let start = s.rangeOfString("\">")?.endIndex
        let end = s.rangeOfString("</")?.startIndex
        
        let result = s.substringWithRange(start!..<end!)
        
        let r = "来自\(result)"
        return getSourceAttr(r)
    }
    
    func getSourceAttr(r:String) -> NSMutableAttributedString{
        let attr = NSMutableAttributedString(string: r)
        
        let range = (r as NSString).rangeOfString("来自")
        
        attr.addAttribute(NSForegroundColorAttributeName, value: ThemeColor, range: range)
        
        return attr
    }
    
    /**
     格式化输出发微博时间
     
     - parameter create_at: create_at
     */
    func getTime(create_at:String) ->String{
        //Thu Jun 30 17:41:04 +0800 2016 "EEE MMM dd HH:mm:ss z yyyy"
        /*
        - 微博时间业务逻辑需求
        - 如果是今年
        - 如果是今天
        -  如果小于60秒 显示格式: 刚刚
        -  如果 s>=60 && s < 60 * 60  显示格式:xx分钟前
        -  如果 s>= 60*60  显示格式: xx小时前
        - 如果是昨天
        -  2016-06-29 12:12:12  显示格式: 昨天 12:12
        - 如果是其他
        -  2016-06-12 13:13:13  显示格式: 06月12日 13:13
        - 如果不是今年
        - 2015-05-05 10:10:10 显示格式: 2015年05月05日 10:10
        */
        let df = NSDateFormatter()
        let dfy = NSDateFormatter()
        //发微博时间全格式
        df.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        //年份的格式
        dfy.dateFormat = "yyyy"
        df.locale = NSLocale(localeIdentifier: "en_US")
        dfy.locale = NSLocale(localeIdentifier: "en_US")
        //微博格式化时间
        let weiboDate = df.dateFromString(create_at)
        //微博年份
        let weiboY = dfy.stringFromDate(weiboDate!)
        //当前年份
        let nowY = dfy.stringFromDate(NSDate())
        //判断是否是今年
        if weiboY == nowY{
            //是今年
            let calender = NSCalendar.currentCalendar()
            if calender.isDateInToday(NSDate()){
                //如果是今天
                //算出秒
                let s = NSDate().timeIntervalSinceDate(weiboDate!)
                if s < 60 {
                    return "刚刚"
                }else if s>=60 && s < 60 * 60 {
                    return "\(Int(s/60))分钟前"
                }else{
                    return "\(Int(s/3600))小时前"
                }
            }else if calender.isDateInYesterday(NSDate()){
                //如果是昨天
                df.dateFormat = "HH:mm"
                return "昨天 \(df.stringFromDate(weiboDate!))"
            }else{
                df.dateFormat = "MMM月dd日 HH:mm"
                return df.stringFromDate(weiboDate!)
            }
        }else{
            //不是今年
            df.dateFormat = "yyyy年MMM月dd日 HH:mm"
            return df.stringFromDate(weiboDate!)
        }
    }
    
    func getWeiBoAttr(text:String) -> NSMutableAttributedString{
        
        let attrString = NSMutableAttributedString(string: text)
        
        var matchArr : [LCWMatchResult] = [LCWMatchResult]()
        
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (count, string, range, _) -> Void in
            let match = LCWMatchResult(string: (string.memory as! String), range: range.memory)
            
            matchArr.append(match)
        }
        
        for match in matchArr.reverse(){
            let emotion = LCWEmotionTools.sharedTools.searchEmotion(match.string)
            
            let att = NSTextAttachment()
            let path = emotion?.path ?? ""
            let png = emotion?.png ?? ""
            let name = path + png
            att.image = UIImage(named: name, inBundle: LCWEmotionTools.sharedTools.emotionBundle, compatibleWithTraitCollection: nil)
            
            let lineHeight = UIFont.systemFontOfSize(15).lineHeight
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            
            let attr = NSAttributedString(attachment: att)
            
            attrString.replaceCharactersInRange(match.range, withAttributedString: attr)
            
            
        }
        
        return attrString
    }
}
